package com.ck.controller.admin;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Teacher;
import com.ck.service.AdminService;

public class AddNewTeacherController extends SimpleFormController {

	private AdminService adminService;

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {

		Teacher teacher = (Teacher) command;
		Map model = errors.getModel();
		
		//后台校验
		boolean flag = true;
		String username = teacher.getUsername().trim();
		String truename = teacher.getTruename().trim();
		String email = teacher.getEmail().trim();
		
		if(username == null || "".equals(username)) {
			model.put("error_username", "请输入账号");
			flag = false;
		}
		
		if(username.length() > 16) {
			model.put("error_username", "账号长度：1-16个字符");
			flag = false;
		}
		
		if(truename == null || "".equals(truename)) {
			model.put("error_truename", "请输入真实姓名");
			flag = false;
		}
		
		if(truename.length() > 12) {
			model.put("error_truename", "真实姓名长度：1-12个字符");
			flag = false;
		}
		
		if( email == null || "".equals(email) ){
			teacher.setEmail(null);
        }else{
	        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
			Matcher m = p.matcher(email);
			if(!m.matches()){
				model.put("error_email", "email格式不正确");
				flag = false;
			}
        }
		
		if(email.length() > 40){
			model.put("error_email", "email长度：0-40个字符");
			flag = false;
		}
		
		//校验不通过
        if(!flag){
        	model.put("username", username);
        	model.put("truename", truename);
        	model.put("email", email);
			return new ModelAndView(getFormView(), model);
		}
		

		boolean isNewTeacher = false;
		isNewTeacher = adminService.addNewTeacher(teacher, model);
		
		if (isNewTeacher) {
            return new ModelAndView(getSuccessView(),model);
        } else {
        	model.put("username", username);
        	model.put("truename", truename);
        	model.put("email", email);
            return new ModelAndView(getFormView(), model);
        }
	}
}
